package com.qingke.pms.command.system;

import java.util.regex.Pattern;

import org.apache.commons.codec.digest.DigestUtils;

import com.qingke.pms.command.SystemCommand;
import com.qingke.pms.pojo.User;
import com.qingke.pms.pojo.UserLogin;
import com.qingke.pms.util.PMSConsole;

public class RegisterCommand extends SystemCommand{

	@Override
	public void execute() {
		String username;
		String password;
		String nickname;
		String email;
		String phone;
		PMSConsole.println("----------------");
		while(true){
			username=PMSConsole.promptNotEmpty("username:");
			if(dao.isUsernameExists(username)){
				PMSConsole.println("The username have been existed.");
				continue;
			}
			break;
		}
		while(true){
			password=PMSConsole.promptNotEmpty("password:");
			try {
				matcherPassword(password);
			} catch (Exception e) {
				PMSConsole.println("Format error:"+e.getMessage());
				continue;
			}
			break;
		}
		nickname=PMSConsole.promptNotEmpty("nickname:");
		email=PMSConsole.promptNotEmpty("email:");
		phone=PMSConsole.promptNotEmpty("phone:");
		PMSConsole.println("----------------");
		UserLogin userLogin=new UserLogin();
		User user=new User();
		userLogin.setUsername(username);
		userLogin.setPassword(DigestUtils.md5Hex(password));
		user.setName(nickname);
		user.setEmail(email);
		user.setPhone(phone);
		boolean isSuccess=dao.register(userLogin, user);
		if(isSuccess)
			PMSConsole.println("Register success.");
		else
			PMSConsole.println("Register failed.");
	}

	private void matcherPassword(String password) throws Exception{
		Pattern lengthPattern = Pattern.compile(".{6,}");
		if(!lengthPattern.matcher(password).find()){
			throw new Exception("The password's length must more than 6.");
		}
		Pattern letterPattern = Pattern.compile("[a-zA-Z]");
		if(!letterPattern.matcher(password).find()){
			throw new Exception("The password must contain at least one English letter.");
		}
		Pattern digitPattern = Pattern.compile("");
		if(!digitPattern.matcher(password).find()){
			throw new Exception("The password must contain at least one digit.");
		}

	}
	
}
